package tech.aichan.AiQA.utils;

import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Sort 构建工具
 * @author mengyu
 * @date 2024/06/04 09:22
 */
public class ESSortBuilder {

    private List<Boolean> booleans;

    private List<String> fields;

    public ESSortBuilder() {
    }

    public ESSortBuilder bool(Boolean... booleans){
        this.booleans = new ArrayList<>(Arrays.asList(booleans));
        return this;
    }

    public ESSortBuilder filed(String... fields){
        this.fields = new ArrayList<>(Arrays.asList(fields));
        return this;
    }

    public void clear(){
        this.fields = null;
        this.booleans = null;
    }

    public Sort builder(){
        Sort sort = Sort.unsorted();
        if(booleans == null || fields == null){
            throw new IllegalArgumentException("booleans and fields can't be null");
        }
        if(booleans.size() != fields.size()){
            throw new IllegalArgumentException("booleans' size and fields' size must be equal");
        }
        for (int i = 0; i < booleans.size(); i++) {
            if(booleans.get(i) != null){
                sort = getSort(fields.get(i), booleans.get(i));
            }
        }
        clear();
        return sort;
    }



    /**
     * Sort构建工具：挑选bool中第一个不为null的字段作为排序字段，true为ASC，false为DESC
     * @param bool bool列表
     * @param filed 字段列表
     * @return  Sort
     */
    public static Sort sortChooseOneBuilder(Iterable<Boolean> bool, Iterable<String> filed){
        Sort sort = Sort.unsorted();
        Iterator<String> iterator = filed.iterator();
        for (Boolean b : bool) {
            if(b != null){
                sort = getSort(iterator.next(), b);
            }
            iterator.next();
        }
        return sort;
    }

    private static Sort getSort(String filed, Boolean asc){
        return asc ? Sort.by(filed).ascending() : Sort.by(filed).descending();
    }

}
